<template>
    <div id="app" style="background-color: #0e2e87" v-if="$route.meta.bigScreen">
        <router-view />
    </div>
    <div id="app" v-else>
        <router-view :key="language" />
        <!-- 告警提示框 -->
        <notification v-if="showNotification" :message="notificationMessage" :showTip="showNotification" />
        <theme-picker />
    </div>
</template>

<script>
import ThemePicker from '@/components/ThemePicker';
import Notification from '@/components/Notification/index';
import { getUserId } from '@/utils/auth';

export default {
    name: 'App',
    components: { ThemePicker, Notification },
    metaInfo() {
        return {
            title: this.$store.state.settings.dynamicTitle && this.$store.state.settings.title,
            titleTemplate: (title) => {
                return title ? `${title} - ${process.env.VUE_APP_TITLE}` : process.env.VUE_APP_TITLE;
            },
        };
    },
    data() {
        return {
            showNotification: false,
            notificationMessage: null,
            appMqttListener: null,
        };
    },
    computed: {
        language() {
            return this.$store.state.settings.language;
        },
        token() {
            return this.$store.state.user.token;
        },
    },
    mounted() {
        // this.connectMqtt();
    },
    // watch: {
    //     token(newToken) {
    //         if (newToken) {
    //             setTimeout(() => {
    //                 this.connectMqtt();
    //             }, 5000);
    //         }
    //     },
    // },
    methods: {
        /* 连接Mqtt消息服务器 */
        connectMqtt() {
            if (this.$mqttTool.client == null) {
                console.log('Connecting to MQTT...');
                this.$mqttTool.connect();
            }
            this.mqttCallback();
            this.$mqttTool.subscribe('/notify/alert/web/push/' + getUserId());
        },

        /* Mqtt回调处理  */
        mqttCallback() {
            const appListener = (topic, message) => {
                try {
                    message = JSON.parse(message.toString());
                    this.notificationMessage = message;
                    if (message.showDialog === 1) {
                        this.showNotification = true;
                    }
                    console.log('Received status', this.notificationMessage);
                    if (!message) {
                        return;
                    }
                } catch (e) {
                    console.error('处理MQTT消息出错:', e);
                }
            };

            // 给app的监听器添加唯一标识
            appListener.isAppListener = true;

            // 保存监听器引用
            this.appMqttListener = appListener;

            // 绑定监听器
            this.$mqttTool.client.on('message', appListener);
        },
    },
    beforeDestroy() {
        this.$mqttTool.unsubscribe('/notify/alert/web/push/' + getUserId());
    },
};
</script>

<style scoped>
#app .theme-picker {
    display: none;
}
</style>
